package com.company.manage.common.security;

import org.springframework.web.util.HtmlUtils;
import org.springframework.web.util.JavaScriptUtils;

import java.beans.PropertyEditorSupport;

/**
 * Created by HuangYong on 2016/1/22.
 * desc: 与spring mvc的@InitBinder结合 用于防止XSS攻击
 */
public class StringEscapeEditor extends PropertyEditorSupport {
    private static final String TAG = "StringEscapeEditor";

    private boolean escapeHTML;//编码HTML
    private boolean escapeJavaScript;//编码javascript

    public StringEscapeEditor() {
        super();
    }

    public StringEscapeEditor(boolean escapeHTML, boolean escapeJavaScript) {
        super();
        this.escapeHTML = escapeHTML;
        this.escapeJavaScript = escapeJavaScript;
    }

    public String getAsText() {
        Object value = getValue();
        return value != null ? value.toString() : "";
    }

    public void setAsText(String text) {
        if (text==null){
            setValue(null);
        }else {
            String value = text;
            if (escapeHTML){
                value = HtmlUtils.htmlEscape(value);
            }
            if (escapeJavaScript){
                value = JavaScriptUtils.javaScriptEscape(value);
            }
            setValue(value);
        }
    }


} 